<template>
  <a-modal
    class="imageOutPainting"
    v-model:visible="visible"
    title="AI扩图"
    :footer="false"
    @cancel="closeModel"
  >
    <a-row gutter="16">
      <a-col span="12">
        <h4>原始图片</h4>
        <img :src="picture.url" :alt="picture.name" style="max-width: 100%" />
      </a-col>
      <a-col span="12">
        <h4>扩图结果</h4>
        <img
          v-if="resultImageUrl"
          :src="resultImageUrl"
          :alt="picture.name"
          style="max-width: 100%"
        />
      </a-col>
    </a-row>
    <div style="margin-bottom: 16px"></div>
    <a-flex justify="center" gap="16">
      <a-button type="primary" ghost :loading="loading" @click="createTask"> 生成图片 </a-button>
      <a-button v-if="resultImageUrl" type="primary" :loading="uploadLoading" @click="handleUpload"
        >应用结果</a-button
      >
    </a-flex>
  </a-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import {
  getPictureOutPaintingTaskResultUsingGet,
  uploadPictureByUrlUsingPost,
} from '@/api/pictureController'
import { createPictureOutPaintingTaskUsingPost } from '@/api/pictureController'
const visible = ref(false)
//任务id，根据任务id查询结果
const taskId = ref<string>()
interface Props {
  picture?: API.PictureVO
  spaceId?: number
  onSuccess?: (newPicture: API.PictureVO) => void
}
const props = defineProps<Props>()
//创建Ai扩图任务
const createTask = async () => {
  loading.value = true
  if (!props.picture?.id) {
    return
  }
  try {
    const res = await createPictureOutPaintingTaskUsingPost({
      pictureId: props.picture.id,
      //设置扩图参数
      parameters: {
        xScale: 2,
        yScale: 2,
      },
    })
    if (res.data.code === 200) {
      message.success('创建任务成功,请耐心等待AI生成结果')
      taskId.value = res.data.data.output.taskId
      //开启轮询
      startPolling()
    } else {
      message.error('上传失败：' + res.data.data.message)
    }
  } catch (error) {
    message.error('上传异常')
  }
  loading.value = false
}

// 轮询定时器
let pollingTimer: ReturnType<typeof setTimeout> | null = null
const startPolling = () => {
  if (!taskId.value) {
    return
  }
  try {
    pollingTimer = setInterval(async () => {
      const res = await getPictureOutPaintingTaskResultUsingGet({
        taskId: taskId.value,
      })
      if (res.data.code === 200) {
        const taskResult = res.data.data.output
        if (taskResult.taskStatus === 'SUCCEEDED') {
          message.success('扩图任务执行成功')
          resultImageUrl.value = taskResult.outputImageUrl
          stopPolling()
        } else if (taskResult.taskStatus === 'FAILED') {
          message.error('扩图任务执行失败')
          stopPolling()
        }
      } else {
        message.error('扩图任务失败，请重试：' + res.data.data)
      }
    }, 3000)
  } catch (error) {
    message.error('轮询异常')
    stopPolling()
  }
}

//清除轮询
const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
    taskId.value = null
  }
}

//获取图片裁切框的引用
const cropperRef = ref(null)

const loading = ref(false)
const resultImageUrl = ref('')

const uploadLoading = ref(false)
/**
 * 上传图片
 * @param file
 */
const handleUpload = async () => {
  uploadLoading.value = true
  try {
    const params: API.PictureUploadDTO = { fileUrl: resultImageUrl.value, spaceId: props.spaceId }
    if (props.picture) {
      params.id = props.picture.id
    }
    const res = await uploadPictureByUrlUsingPost(params)
    if (res.data.code === 200) {
      message.success('上传成功')
      props.onSuccess?.(res.data.data)
      closeModel()
    } else {
      message.error('上传失败：' + res.data.data)
    }
  } catch (error) {
    message.error('上传异常')
  }
  uploadLoading.value = false
}

// 打开弹窗
function openModel() {
  visible.value = true
}
// 关闭弹窗
const closeModel = () => {
  visible.value = false
}
defineExpose({ openModel })
</script>

<style scoped>
.imageOutPainting {
  text-align: center;
}
</style>